import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { CommonSmsModule } from './common/services/sms.module';
import { DevicesModule } from './devices/devices.module';
import { UsersModule } from './users/users.module';
import { TagsModule } from './tags/tags.module';
import { AttachmentsModule } from './attachments/attachments.module';
import { TasksModule } from './tasks/tasks.module';
import { ContentsModule } from './contents/contents.module';
import { DeviceAuditModule } from './device-audit/device-audit.module';
import { LoginModule } from './login/login.module';

import { TDeviceModule } from './t_device/t-device.module';
import { TokenModule } from './token/token.module';
import { PermissonModule } from './permisson/permisson.module';
import { TUserModule } from './t_user/t-user.module';


@Module({
  imports: [
    // Load environment variables
    ConfigModule.forRoot({
      isGlobal: true,
    }),

    // Database configuration
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        type: 'postgres',
        host: configService.get('DB_HOST'),
        port: configService.get('DB_PORT'),
        username: configService.get('DB_USERNAME'),
        password: configService.get('DB_PASSWORD'),
        database: configService.get('DB_DATABASE'),
        entities: [__dirname + '/**/*.entity{.ts,.js}'],
        // Use synchronize in development only, migrations in production
        synchronize:
          configService.get('NODE_ENV') !== 'production' &&
          configService.get('DB_SYNCHRONIZE') === 'true',
        // Load migrations in production or when synchronize is disabled
        migrationsRun:
          configService.get('NODE_ENV') === 'production' ||
          configService.get('DB_SYNCHRONIZE') !== 'true',
        // Use the correct file extension based on environment
        migrations: [
          configService.get('NODE_ENV') === 'production'
            ? __dirname + '/migrations/**/*.js'
            : __dirname + '/migrations/**/*.{ts,js}',
        ],
      }),
    }),

    // Feature modules
    AuthModule,
    CommonSmsModule,
    DevicesModule,
    UsersModule,
    TagsModule,
    AttachmentsModule,
    TasksModule,
    ContentsModule,
    DeviceAuditModule,
    LoginModule,
    TDeviceModule,
    TokenModule,
    PermissonModule,
    TUserModule,
  ],
})
export class AppModule {}
